package com.tgy.JUC.Single;

import java.lang.reflect.Constructor;

/***
 * @ClassName: LazyManUnafse22
 * @Description:
 * @Auther: 送你一块二向箔
 * @Date: 17:41 2022/3/15
 * @version : V1.0
 */
public class LazyManUnafse2 {
    private static LazyManUnafse2 lazyManUnafse2;
    //定义一个flag来解决都从反射构建的问题
    private static boolean flag = false;

    private LazyManUnafse2() {
        //改进代码饰得利用反射也不能破坏单例
        synchronized (LazyManUnafse2.class){
            if(flag == false){
                flag = true;
            }else{
                throw new RuntimeException("不要试图利用反射破坏异常");
            }
        }
        
        System.out.println(Thread.currentThread().getName()+"ok");
    }

    public static LazyManUnafse2 getInstance() {
        if (lazyManUnafse2 == null) {
            lazyManUnafse2 = new LazyManUnafse2();
        }
        return lazyManUnafse2;
    }

    public static void main(String[] args) throws Exception {
        //LazyManUnafse2 instance = LazyManUnafse2.getInstance();
        Constructor<LazyManUnafse2> declaredConstructor = LazyManUnafse2.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);//无视私有构造器
        LazyManUnafse2 lazyManUnafse1= declaredConstructor.newInstance();
        LazyManUnafse2 lazyManUnafse2 = declaredConstructor.newInstance();
        //两个都用反射加锁限制不了
        System.out.println(lazyManUnafse1.hashCode());
        System.out.println(lazyManUnafse2.hashCode());

    }
}
